package com.greenantmall.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.greenantmall.R;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.adapter.OrderDetailListAdapter;
import com.greenantmall.bean.MyMsg;
import com.greenantmall.bean.Order;
import com.greenantmall.bean.OrderItem;
import com.greenantmall.bean.OrderStatusCode;
import com.greenantmall.bean.ShippingAddr;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.NotificationUtil;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.view.CommonDialog;
import com.lsarah.utils.SystemBarTintManager;

public class OrderDetailActivity extends BaseActivity
{
    public static final String KeySendTime = "key_send_time";
    public static final String KeyGoodsList = "key_goods_list";
    private final String TAG = "OrderDetailActivity";

    private ShippingAddr mShippingAddr;

    private View mBackView;

    private TextView mTvShouldPayMoney;
    // 订单号
    private TextView order_detail_number_desc;

    private TextView order_send_way;
    private TextView order_create_time;
    private TextView order_send_time;
    private TextView order_send_method;
    // 订单状态
    private TextView order_detail_status;
    private TextView  order_ship_price;
    private TextView  order_minus_price;//优惠金额
    
    private TextView receiverNameTv;
    private TextView receiverTelTv;
    private TextView receiverAddrTv;

    private TextView order_storeName;
    private TextView makeCallTitle;
    private Button makeaCall;

    private Button close;
    private Button payContinue;

    // private Order order;
    private Context context;
    private ScrollView scrollView;

    private ListView orderlist;
    private List<OrderItem> orderItemList = new ArrayList<OrderItem>();
    OrderDetailListAdapter orderDetailListAdapter;
    private View order_refresh;
    // 电话号码
    private String teleP = "";

    private RelativeLayout nodataView;
    private LinearLayout dataView;

    private Handler mHandler = new Handler();

    private OnClickListener mOnClickListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            if (v.equals(mBackView))
            {
                OrderDetailActivity.this.finish();
            }
        }
    };

    private RetrieveDataListener mRetrieveDataListener = new RetrieveDataListener()
    {
        @Override
        public void dataRetrieved(int requestId, Object data)
        {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        SystemBarTintManager.setContentView(this, R.layout.order_detail,
            getResources().getColor(R.color.green));
        context = this;
        mBackView = findViewById(R.id.order_create_top_arrow_left);
        // mBtnCreateOrder = (Button) findViewById(R.id.order_create_btn);
        mTvShouldPayMoney = (TextView) findViewById(R.id.order_create_should_pay_money);
        // mTvTotalMoney = (TextView)
        // findViewById(R.id.order_create_total_money);
        order_detail_number_desc = (TextView) findViewById(R.id.order_detail_number_desc);
        order_create_time = (TextView) findViewById(R.id.order_create_time);
        order_detail_status = (TextView) findViewById(R.id.order_detail_status);
        close = (Button) findViewById(R.id.close);
        payContinue = (Button) findViewById(R.id.payContinue);
        makeaCall = (Button) findViewById(R.id.makeaCall);
        orderlist = (ListView) findViewById(R.id.orderlist);
        order_refresh = findViewById(R.id.order_refresh);
        scrollView = (ScrollView) findViewById(R.id.scrollView);

        nodataView = (RelativeLayout) findViewById(R.id.nodataView);
        dataView = (LinearLayout) findViewById(R.id.dataView);

        order_send_way = (TextView) findViewById(R.id.order_send_way);
        order_storeName = (TextView) findViewById(R.id.order_storeName);
        makeCallTitle= (TextView) findViewById(R.id.makeCallTitle);
        
        receiverNameTv = (TextView) findViewById(R.id.order_receiver_name);
        receiverTelTv = (TextView) findViewById(R.id.order_receiver_tel);
        receiverAddrTv = (TextView) findViewById(R.id.order_receiver_addr);
        
        order_send_time= (TextView) findViewById(R.id.order_send_time);
        order_send_method= (TextView) findViewById(R.id.order_send_method);
        order_ship_price= (TextView) findViewById(R.id.order_ship_price);
        order_minus_price=(TextView) findViewById(R.id.order_minus_price);
        mBackView.setOnClickListener(mOnClickListener);
        // mBtnCreateOrder.setOnClickListener(mOnClickListener);
        orderDetailListAdapter = new OrderDetailListAdapter(orderItemList, this);

        orderlist.setAdapter(orderDetailListAdapter);
        order_refresh.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                dataView.setVisibility(View.INVISIBLE);
                nodataView.setVisibility(View.VISIBLE);
                if (Const.order != null)
                {

                    RetrieveDataAsyn.getInstance().getOrderDetail(
                        Const.order.getObjectId(), 0, new RetrieveDataListener()
                    {

                        @Override
                        public void dataRetrieved(int requestId,
                            Object data)
                        {

                            if (data != null)
                            {
                                Order tempOrder = (Order) data;
                                
                                Const.order.put(Order.ATTR_ORDERITEMS,  tempOrder.getString(Order.ATTR_ORDERITEMS));
                                List<OrderItem> tempList = Const.order.getOrderItems();
                                List<OrderItem> tempList1 = tempOrder.getOrderItems();
                                for(int i=0;i<tempList1.size();i++)
                                {
                                    Log.d(TAG, "tempList1:"+tempList1.get(i).getWeight());
                                }
                                tempList.clear();
                                tempList.addAll(
                                    tempOrder.getOrderItems());
                                orderItemList.clear();
                                orderItemList.addAll(tempOrder
                                    .getOrderItems());

                                Const.order.setStatusCode(tempOrder
                                    .getStatusCode());
                                Const.order.setAddress(tempOrder.getAddress());
                                Const.order.setOrderType(tempOrder
                                    .getOrderType());
                                Const.order.setPayWay(tempOrder.getPayWay());
                                Const.order.setDeliveryTime(tempOrder
                                    .getDeliveryTime());
                                Const.order.setDeliveryWay(tempOrder
                                    .getDeliveryWay());
                                Const.order.setPayTime(tempOrder.getPayTime());
                                Const.order.setTotalCost(tempOrder
                                    .getTotalCost());
                                Const.order.setDeliveryCost(tempOrder
                                    .getDeliveryCost());
                                Const.order.setPayed(tempOrder.isPayed());
                                orderDetailListAdapter
                                    .notifyDataSetChanged();
                               

                                initData();

                            }
                            dataView.setVisibility(View.VISIBLE);
                            nodataView.setVisibility(View.INVISIBLE);

                        }
                    });

                } else
                {
                    dataView.setVisibility(View.VISIBLE);
                    nodataView.setVisibility(View.INVISIBLE);
                }

            }
        });
        // read data from intent
        initData();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        Intent intent=new Intent(Const.ORDER_STATUS_CHANGED);
        sendBroadcast(intent);
    }

    private void initData()
    {
        if (Const.order == null)
        {
            return;
        }
        // order = Const.order;

        // 订单创建时间
        order_create_time.setText(DateFormat.format("yyyy-MM-dd HH:mm:ss",
            Const.order.getCreatedAt()));
        // // 订单号
        order_detail_number_desc.setText(Const.order.getOrderId());

        orderItemList.clear();
        List<OrderItem> items = Const.order.getOrderItems();
        orderItemList.addAll(items);
        
        for(int i=0;i<items.size();i++)
        {
            Log.d(TAG, "tempList1 items:"+items.get(i).getWeight());
        }
        
        String totalCost = UtilTools.getTotalCostByOrderItems(orderItemList);
        double tempTotal=Double.parseDouble(totalCost);
        DecimalFormat df = new DecimalFormat("#########.##");
        // 应付总金额
        if ( tempTotal< 0.00001)
        {
            mTvShouldPayMoney.setText("--.--");
        } else
        {
        	tempTotal+=Const.order.getDeliveryCost();
        	tempTotal-=Const.order.getFavorableCost();
            mTvShouldPayMoney.setText(df.format(tempTotal));
        }
        order_ship_price.setText("￥"+Const.order.getDeliveryCost());
        order_minus_price.setText("￥"+Const.order.getFavorableCost());
        setListViewHeight(orderlist);
        orderDetailListAdapter.notifyDataSetChanged();
        
        try
        {
            teleP = String.valueOf(AntHomeApplication.serviePhone.getPhone());
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        order_storeName.setVisibility(View.VISIBLE);
        String deliveryWay=Const.order.getDeliveryWay();
       
        if (Const.order.isSp())
        {
            
            
        } else
        {
            try
            {
                order_storeName.setText(AntHomeApplication.storeInfos.get(
                    Const.order.getStoreId()).getDescrip());
                
                teleP = AntHomeApplication.storeInfos.get(Const.order.getStoreId())
                    .getPhone();
            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }
        if(this.getString(R.string.order_ensure_send_metho_ziting).equals(deliveryWay))
        {
        	String pickUpId=Const.order.getPickUpStationId();
            if(!TextUtils.isEmpty(pickUpId))
            {
                order_storeName.setText(String.format(this.getString(R.string.orderdetail_pickup), pickUpId)); 
            }
        }
        order_send_method.setText(deliveryWay);
        Date deliverTime=Const.order.getDeliveryTime();
        if(deliverTime.getTime()<=System.currentTimeMillis())
        {
            order_send_time.setText(R.string.order_ensure_send_time_right_now);    
        }else{
            order_send_time.setText(DateFormat.format("yyyy-MM-dd HH:mm:ss",
                deliverTime)); 
        }
        
        if (TextUtils.isEmpty(teleP))
        {
            makeaCall.setVisibility(View.GONE);
            makeCallTitle.setVisibility(View.GONE);
        }
        // 支付方式
        order_send_way.setText(Const.order.getPayWay());
        
        receiverNameTv.setText(Const.order.getConsignee());
        receiverTelTv.setText(Const.order.getPhone());
        receiverAddrTv.setText(Const.order.getAddress());
        
        processOrderStatus();
        mHandler.postDelayed(new Runnable()
        {

            @Override
            public void run()
            {
                scrollView.scrollTo(0, 0);
            }
        }, 200);

    }

    public void makeaCall(View view)
    {

        if (!TextUtils.isEmpty(teleP))
        {
            CommonDialog errDialog = new CommonDialog(context,
                R.style.ExitDialogStyle,
                context.getString(R.string.common_title),
                context.getString(R.string.orderdetail_call));
            errDialog.setSureListener(new CommonDialog.OnSureClickListener()
            {

                @Override
                public void sureClicked()
                {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri
                        .parse("tel:" + teleP));
                    startActivity(intent);
                }
            });
            errDialog.show();

        }

    }

    /**
     * 重新计算ListView的高度，解决ScrollView和ListView两个View都有滚动的效果，在嵌套使用时起冲突的问题
     * @param listView
     */
    public void setListViewHeight(ListView listView)
    {

//        if(true)
//            return;
        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null)
        {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++)
        { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
//            listItem.getHeight();
 //           totalHeight +=listItem.getHeight(); // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 处理初始订单状态界面，button，status，注册监听等
     * @since 3.8
     */
    private void processOrderStatus()
    {

        processOrderButton();

    }

    /**
     * 处理button，status,刷新界面
     * @since 3.8
     */
    private void processOrderButton()
    {

        UtilTools.processOrderStatus(close, payContinue, order_detail_status, context, Const.order);
        UtilTools.processOrderButtonClick(close, payContinue, order_detail_status, context, Const.order, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d("CEXX", "CEXX ---> OrderCreateActivity ---> requestCode : "
            + requestCode);
        Log.d("CEXX", "CEXX ---> OrderCreateActivity ---> resultCode : "
            + resultCode);
        if (data != null)
        {
            String name = data
                .getStringExtra(MyAddressEditActivity.KEY_ADDRESS_NAME);
            String mobile = data
                .getStringExtra(MyAddressEditActivity.KEY_ADDRESS_MOBILE);
            String uptown = data
                .getStringExtra(MyAddressEditActivity.KEY_ADDRESS_UPTOWN);
            String door = data
                .getStringExtra(MyAddressEditActivity.KEY_ADDRESS_DOOR);

            name = (name == null ? "" : name);
            mobile = (mobile == null ? "" : mobile);
            uptown = (uptown == null ? "" : uptown);
            door = (door == null ? "" : door);

            mShippingAddr = new ShippingAddr();
            mShippingAddr.setUserId(AVUser.getCurrentUser().getObjectId());
            mShippingAddr.setDoor(door);
            mShippingAddr.setMobile(mobile);
            mShippingAddr.setName(name);
            mShippingAddr.setUptown(uptown);
        }
    }

}
